// 默认缓存期限为7天
const DEFAULT_CACHE_TIME = 60 * 60 * 24;

// 类型定义
type StorageConfig = {
  prefixKey?: string;
  storage?: globalThis.Storage;
};

type StorageData = {
  value: any;
  expire: number | null;
};

//创建带有配置的存储函数
const createStorage = (config: StorageConfig = {}) => {
  const { prefixKey = "", storage = localStorage } = config;

  // 生成带前缀的key
  const getKey = (key: string) => `${prefixKey}${key}`.toUpperCase();

  // 存储操作
  const set = (
    key: string,
    value: any,
    expire: number | null = DEFAULT_CACHE_TIME,
  ) => {
    const stringData = JSON.stringify({
      value,
      expire: expire !== null ? Date.now() + expire * 1000 : null,
    });
    storage.setItem(getKey(key), stringData);
  };

  const get = (key: string, def: any = null) => {
    const item = storage.getItem(getKey(key));
    if (!item) return def;

    try {
      const data: StorageData = JSON.parse(item);
      const { value, expire } = data;
      // 在有效期内直接返回
      if (expire === null || expire >= Date.now()) {
        return value;
      }
      remove(key);
      return def;
    } catch (e) {
      return def;
    }
  };

  const remove = (key: string) => {
    storage.removeItem(getKey(key));
  };

  const clear = () => {
    storage.clear();
  };

  // Cookie操作
  const setCookie = (
    name: string,
    value: any,
    expire: number | null = DEFAULT_CACHE_TIME,
  ) => {
    document.cookie = `${getKey(name)}=${value}; Max-Age=${expire}`;
  };

  const getCookie = (name: string): string => {
    const cookieArr = document.cookie.split("; ");
    for (const cookie of cookieArr) {
      const [k, v] = cookie.split("=");
      if (k === getKey(name)) {
        return v;
      }
    }
    return "";
  };

  const removeCookie = (key: string) => {
    setCookie(key, 1, -1);
  };

  const clearCookie = () => {
    const keys = document.cookie.match(/[^ =;]+(?==)/g);
    if (keys) {
      keys.forEach((key) => {
        document.cookie = `${key}=0;expire=${new Date(0).toUTCString()}`;
      });
    }
  };

  // 返回所有方法
  return {
    getKey,
    set,
    get,
    remove,
    clear,
    setCookie,
    getCookie,
    removeCookie,
    clearCookie,
  };
};

// 默认实例
export const storage = createStorage();
